import { defineStore } from "pinia";
import { ref } from "vue";
import { getToken, setToken, removeToken } from "@/utils/auth";

export const useUserStore = defineStore("user", () => {
  const token = ref(getToken());
  const name = ref("");
  const nickname = ref("");
  const userId = ref("");
  const avatar = ref("");
  const roles = ref([]); // 用户角色编码集合 → 判断路由权限
  const permissions = ref([]); // 用户权限编码集合 → 判断按钮权限
  const identityType = ref("22"); 
  /** 保存用户信息 */
  const saveUserInfo = (info) => {
    token.value = info.token;
    name.value = info.name;
    if(info.identityType == 1){
      nickname.value = info.nickname;
    }
    userId.value = info.userId;
    avatar.value = info.avatar;
    roles.value = info.roles;
    permissions.value = info.permissions;
    identityType.value = info.identityType
    setToken(info.token);
  };

  /** 删除用户信息 */
  const removeUserInfo = () => {
    token.value = undefined;
    name.value = undefined;
    nickname.value = undefined;
    userId.value = undefined;
    avatar.value = undefined;
    roles.value = [];
    permissions.value = [];
    identityType.value = undefined
    removeToken();
  };

  return {
    userId,
    token,
    nickname,
    avatar,
    roles,
    permissions,
    identityType,
    saveUserInfo,
    removeUserInfo,
  };
});

export default useUserStore;
